package com.example.demo.controller;

import com.example.demo.entity.Artical;
import com.example.demo.entity.User;
import com.example.demo.mapper.ArticalMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Calendar;

@Controller  //RestController 显示数据
public class LoginController {


    //对外暴漏的永远是接口
    @Autowired
    UserService userService;


    @GetMapping("/toLoginPage")
    public String toLoginPage(Model model) {
        System.out.println(Calendar.getInstance().get(Calendar.YEAR));
        model.addAttribute("error", "");
        // Artical artical = articalMapper.findByid(1);
        // model.addAttribute("artical", artical);

        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        //application prefix: classpath:/templates/page/
        //suffix: .html
        return "page/login";
    }


    //登陆状态是保存在浏览器的cookie  和服务器的session中
    @Autowired
    HttpServletRequest request;

    @PostMapping("/toLogin")
    //User  为了接受页面数据（页面上的参数名和对象的属性名一致）
    //model 为了后台向前台传数据 注意提交表单用PostMapping
    public String toIndex(User user, Model model) {
        HttpSession session = request.getSession();
        String path = "";

        User loginUser = userService.login(user);
        if (loginUser != null) {
            session.setAttribute("user", loginUser);
            model.addAttribute("username", loginUser.username);
            return "redirect:/toIndex";
        } else {
            model.addAttribute("error", "用户名密码错误");
            path = "page/login";
        }
        return path;
    }


    @GetMapping("/toIndex")
    public String toIndexPage() {
        return "page/index";
    }


    /**
     * 退出系统删除登录用户的会话
     *
     * @param request
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("user", null);
        //session.removeAttribute("user");
        return "page/login";
    }


}
